package org.db.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.db.Manager;
import org.db.dao.GleisDAO;
import org.db.dao.change.AddProjektElement;
import org.db.dao.change.RemoveProjektElement;

/**
 * 
 * @author Lutz
 */
public class GleisDefinitionDialog extends CloseCommitDialog
		implements
			ActionListener,
			DocumentListener,
			KeyListener,
			MouseListener {

	private static final long serialVersionUID = -541709354917589528L;

	private int anzahlGleise;

	private GleisDAO element2Edit = null;

	public GleisDefinitionDialog(JDialog owner, int anzahlGleise) {
		super(owner);
		this.anzahlGleise = anzahlGleise;
		setTitle("Definition der Gleise");
		initComponents();
		setModal(true);
	}

	private static final String AbstandKMException = "Bitte geben Sie für dieses Gleis einen Abstand zur km- Linie ein!";

	@SuppressWarnings({"rawtypes", "unchecked"})
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jScrollPane1 = new javax.swing.JScrollPane();
		table = new GleisDefinitionTable();
		table.addKeyListener(this);
		jButtonCancel = new javax.swing.JButton();
		jButtonOK = new javax.swing.JButton();
		jComboBox1 = new javax.swing.JComboBox();
		jTextGleisBez = new javax.swing.JTextField();
		jTextStation = new DoubleTextField();
		jTextStation.getDocument().addDocumentListener(this);
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jTextKmLinie = new DoubleTextField();
		jButtonGleis = new javax.swing.JButton();

		jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
		jLabel1.setText("Definition der Gleise");

		jTextKmLinie.setVisible(false);

		jScrollPane1.setViewportView(table);

		jButtonCancel.setFont(new java.awt.Font("Tahoma", 1, 12));
		jButtonCancel.setText("Zurück");
		jButtonCancel.addActionListener(this);
		jButtonCancel.addKeyListener(this);

		jButtonOK.setFont(new java.awt.Font("Tahoma", 1, 12));
		jButtonOK.setText("Weiter");
		jButtonOK.addActionListener(this);
		jButtonOK.addKeyListener(this);

		jComboBox1.setFont(new java.awt.Font("Tahoma", 1, 12));
		List<String> gleisIds = new ArrayList<String>();
		for (int i = 501; i <= (500 + anzahlGleise); i++) {
			gleisIds.add(Integer.valueOf(i).toString());
		}
		jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(
				(String[]) gleisIds.toArray(new String[gleisIds.size()])));
		jComboBox1.setSelectedIndex(0);
		jComboBox1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JComboBox jComboBox1 = (JComboBox) e.getSource();
				String id = (String) jComboBox1.getSelectedItem();
				int selectedIndex = jComboBox1.getSelectedIndex();
				if ("501".equals(id)) {
					jTextGleisBez.setText("linkes Gleis");
					jLabel3.setVisible(false);
					jTextKmLinie.setVisible(false);
					jTextKmLinie.setValue(0d);
				} else if ("502".equals(id)) {
					jTextGleisBez.setText("rechtes Gleis");
					jLabel3.setVisible(true);
					jTextKmLinie.setVisible(true);
				} else {
					jTextGleisBez.setText("Gleis "
							+ String.valueOf(Integer.valueOf(id) - 500));
					jLabel3.setVisible(false);
					jTextKmLinie.setVisible(false);
					jTextKmLinie.setValue(0d);
				}
				if (table.getGleisElemente().size() > selectedIndex) {
					fillInputFields(table.getGleisElemente().get(selectedIndex));
				}

			}
		});

		jTextGleisBez.setFont(new java.awt.Font("Tahoma", 1, 12));
		jTextGleisBez.setText("linkes Gleis");

		jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel2.setText("Anfangsstation");

		jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel3.setText("Abstand zur km- Linie");
		jLabel3.setVisible(false);

		jButtonGleis.setFont(new java.awt.Font("Tahoma", 1, 12));
		jButtonGleis.setEnabled(false);
		jButtonGleis.setText("Übernehmen");
		jButtonGleis.addActionListener(this);
		jButtonGleis.addKeyListener(this);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.TRAILING)
												.addComponent(
														jButtonGleis,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														117,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addGroup(
														javax.swing.GroupLayout.Alignment.LEADING,
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.TRAILING)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jButtonCancel,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										86,
																										javax.swing.GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED))
																				.addGroup(
																						javax.swing.GroupLayout.Alignment.LEADING,
																						layout.createSequentialGroup()
																								.addGroup(
																										layout.createParallelGroup(
																												javax.swing.GroupLayout.Alignment.LEADING)
																												.addGroup(
																														layout.createSequentialGroup()
																																.addComponent(
																																		jTextGleisBez,
																																		javax.swing.GroupLayout.PREFERRED_SIZE,
																																		112,
																																		javax.swing.GroupLayout.PREFERRED_SIZE)
																																.addGap(36,
																																		36,
																																		36)
																																.addGroup(
																																		layout.createParallelGroup(
																																				javax.swing.GroupLayout.Alignment.LEADING)
																																				.addComponent(
																																						jLabel2)
																																				.addComponent(
																																						jTextStation,
																																						javax.swing.GroupLayout.PREFERRED_SIZE,
																																						79,
																																						javax.swing.GroupLayout.PREFERRED_SIZE)))
																												.addComponent(
																														jLabel1))
																								.addGap(38,
																										38,
																										38)
																								.addGroup(
																										layout.createParallelGroup(
																												javax.swing.GroupLayout.Alignment.LEADING)
																												.addComponent(
																														jTextKmLinie,
																														javax.swing.GroupLayout.PREFERRED_SIZE,
																														69,
																														javax.swing.GroupLayout.PREFERRED_SIZE)
																												.addComponent(
																														jLabel3))
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																										261,
																										Short.MAX_VALUE))
																				.addComponent(
																						jComboBox1,
																						javax.swing.GroupLayout.Alignment.LEADING,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						javax.swing.GroupLayout.DEFAULT_SIZE,
																						javax.swing.GroupLayout.PREFERRED_SIZE))
																.addComponent(
																		jButtonOK,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		83,
																		javax.swing.GroupLayout.PREFERRED_SIZE))
												.addComponent(
														jScrollPane1,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														759, Short.MAX_VALUE))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jLabel1)
								.addGap(18, 18, 18)
								.addComponent(jComboBox1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(30, 30, 30)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel2)
												.addComponent(jLabel3))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														jTextGleisBez,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jTextStation,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jTextKmLinie,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
										46, Short.MAX_VALUE)
								.addComponent(jButtonGleis,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										32,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jScrollPane1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										145,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														jButtonOK,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														30,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jButtonCancel,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														32,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addContainerGap()));
		validateInput();
		pack();
		setLocationRelativeTo(null);
		jComboBox1.setSelectedIndex(0);
	}

	private void fillInputFields(GleisDAO dao) {
		if (dao != null) {
			jTextStation.setValue(dao.getAnfangsStation());
			jTextKmLinie.setValue(dao.getAbstandKmLinie());
		}
	}

	private boolean stationInput() {
		return !jTextStation.getText().isEmpty();
	}

	private void validateStation() {
		jButtonGleis.setEnabled(stationInput());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jButtonOK) {
			returnValue = JOptionPane.OK_OPTION;
			close();
		} else if (e.getSource() == jButtonCancel) {
			askForClosing();
		} else if (e.getSource() == jButtonGleis) {
			if (isValidInput()) {
				int gleisID = Integer.valueOf(jComboBox1.getSelectedItem()
						.toString());
				String gleisBezeichnung = jTextGleisBez.getText();
				double anfangsStation = jTextStation.getValue();
				double abstandKmLinie = jTextKmLinie.getValue();

				int rowIndex = jComboBox1.getSelectedIndex();
				if ((table.getGleisElemente().size() > rowIndex)
						&& table.getGleisElemente().get(rowIndex) != null) {
					// GleisDAO dao =
					// table.getGleisElemente().get(jComboBox1.getSelectedIndex());
					// dao.setAnfangsStation(anfangsStation);
					// dao.setAbstandKmLinie(abstandKmLinie);
					// table.refresh();
					table.setValueAt(anfangsStation, rowIndex, 2);
					table.setValueAt(abstandKmLinie, rowIndex, 3);
				} else {
					GleisDAO dao = new GleisDAO(gleisID, gleisBezeichnung,
							anfangsStation, abstandKmLinie);
					table.addGleisElement(dao);
					// Manager.getInstance().addDAO2Add(dao);
					Manager.getInstance().addProjektChange(
							new AddProjektElement(dao));
				}

				switchComboBox();
				// if(table.getGleisElemente().size() == anzahlGleise){
				// jButtonGleis.setEnabled(false);
				// }
				validateInput();
				jTextStation.requestFocusInWindow();
			}
		}
	}

	/**
	 * Prüfung ob für das rechte Gleis der Abstand zu km-Linie vorhanden ist
	 */
	public boolean isValidInput() {
		if (jComboBox1.getSelectedItem().equals("502")) {
			if (jTextKmLinie.getText().isEmpty()) {
				JOptionPane.showMessageDialog(this, AbstandKMException,
						"Abstand km- Linie", JOptionPane.WARNING_MESSAGE);
				return false;
			}

		}
		return true;
	}

	public int showDialog() {
		setVisible(true);
		return returnValue;
	}

	/**
	 * ButtonOk ist erst verwendbar, wenn alle Gleise definiert wurden
	 */
	private void validateInput() {
		jButtonOK.setEnabled(table.getGleisElemente().size() == anzahlGleise);
	}

	/**
	 * nach Definition eines Gleises, automatischer Wechsel zum folgenden Gleis
	 */
	private void switchComboBox() {
		int i = Integer.valueOf(jComboBox1.getSelectedItem().toString()) + 1;
		jComboBox1.setSelectedItem(Integer.valueOf(i).toString());
	}

	private void deleteSelectedRow() {
		int selectedRowIndex = table.getSelectedRow();
		if (selectedRowIndex > -1) {
			GleisDAO removedDAO = table.removeGleisElement(selectedRowIndex);
			Manager.getInstance().addProjektChange(
					new RemoveProjektElement(removedDAO));
			validateInput();
			jComboBox1.setSelectedIndex(selectedRowIndex);
		}

	}

	public static String getAbstandKMError() {
		return AbstandKMException;
	}

	private javax.swing.JButton jButtonCancel;

	private javax.swing.JButton jButtonGleis;

	private javax.swing.JButton jButtonOK;

	@SuppressWarnings("rawtypes")
	private javax.swing.JComboBox jComboBox1;

	private javax.swing.JLabel jLabel1;

	private javax.swing.JLabel jLabel2;

	private javax.swing.JLabel jLabel3;

	private javax.swing.JScrollPane jScrollPane1;

	private GleisDefinitionTable table;

	private javax.swing.JTextField jTextGleisBez;

	private DoubleTextField jTextKmLinie;

	private DoubleTextField jTextStation;

	@Override
	public void changedUpdate(DocumentEvent e) {
		validateStation();

	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		validateStation();

	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		validateStation();

	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getSource() == table) {
			if (e.getKeyCode() == KeyEvent.VK_DELETE) {
				deleteSelectedRow();
			}
		} else if (e.getSource() == jButtonGleis) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				jButtonGleis.doClick();
			}
		} else if (e.getSource() == jButtonCancel) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				jButtonCancel.doClick();
			}
		} else if (e.getSource() == jButtonOK) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				jButtonOK.doClick();
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {

	}

	@Override
	public void keyTyped(KeyEvent arg0) {

	}

	@Override
	public void mouseClicked(MouseEvent arg0) {

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {

	}

	@Override
	public void mouseExited(MouseEvent arg0) {

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// bei Doppelklick auf eine Zeile in der Tabelle die Daten des
		// zugehörigen Elements in den Eingabefeldern anzeigen
		if (e.getClickCount() == 2) {
			int row = table.rowAtPoint(e.getPoint());
			element2Edit = table.getElementAtRow(row);
			if (element2Edit != null) {
				loadElement(element2Edit);
			}
		}
	}

	private void loadElement(GleisDAO dao) {
		jTextKmLinie.setVisible(false);
		jTextStation.setValue(dao.getAnfangsStation());
		jTextGleisBez.setText(dao.getBezeichnung());
		if (dao.getAbstandKmLinie() != 0) {
			jTextKmLinie.setVisible(true);
			jTextKmLinie.setValue(dao.getAbstandKmLinie());
		}
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {

	}
}
